const path = require("path");
const fs = require("fs");
const {
  ROOT_DIR,
  PROJECT_NAME,
  TODAY,
  MEDIA_FILE_FORMAT,
  EXTRA_IGNORE_FILE,
} = require("./config");

const getIgnoreList = async (extra = []) => {
  const ignoreFilePath = path.join(ROOT_DIR, ".gitignore");
  if (!fs.existsSync(ignoreFilePath)) {
    return [];
  }
  const ignoreList = await fs.promises
    // 读取 .gitignore 文件，将返回的 Buffer 解码为 utf8 编码的字符串
    .readFile(ignoreFilePath, { encoding: "utf8" })
    // 将字符串按行分割，去除空行和注释行，处理出需要忽略的文件路径列表
    .then((data) => {
      data = data.split("\n").filter((rule) => !rule.startsWith("#") && rule);
      data = [...data, ...extra];
      data = data.map((rule) => {
        if (typeof rule != "string") {
          return rule;
        }
        // 将忽略规则转换为绝对路径, 去掉rule中的换行符
        rule = rule.replace(/\r|\n/g, "");
        return path.join(ROOT_DIR, rule);
      });
      return data;
    })
    .catch((err) => {
      console.error("Error reading .gitignore file", err);
      process.exit(1);
    });
  return ignoreList;
};

/**
 * 将文件格式转为UTF-16 LE编码
 */
const convertToUTF16LE = (str) => {
  const buf = Buffer.from(str, "utf16le");
  return buf.toString("utf16le");
};

module.exports = {
  getIgnoreList,
  convertToUTF16LE,
};
